<?php
use Carbon\Carbon;

if (!function_exists('getTime')) {
    function getTime($time, $status = True)
    {
        $newTime = new Carbon($time);

        if ($status) {
            return $newTime->startOfDay();
        }
        return $newTime->endOfDay();
    }
}

if (!function_exists('str2arr')) {
    /**
     * 字符串转换成数组
     *
     * @param $string
     * @param $delimiter
     * @return array
     */
    function str2arr($string, $delimiter = PHP_EOL)
    {

        $items = explode($delimiter, $string);

        foreach ($items as $key => &$item) {

            // 查找 # 的位置
            $pos = strpos($item, '#');

            if ($pos === 0) {
                // # 开头, 整行注释
                unset($items[$key]);
                // 直接到下一个
                continue;
            }

            if ($pos > 0) {
                // # 在中间, 后面一段注释
                $item = substr($item, 0, $pos);
            }

            $item = trim($item);
            if (empty($item)) {
                unset($items[$key]);
            }

        }

        return $items;
    }
}

if (!function_exists('arr2str')) {
    /**
     * 一维数组转换为字符串
     *
     * @param $string
     * @param $delimiter
     * @return array
     */
    function arr2str($string, $delimiter = PHP_EOL)
    {
        $items = $string;
        if(is_array($string)){
            $items = implode($delimiter, $string);
        }
        return $items;
    }
}

if (!function_exists('convert2Utf8')) {
    /**
     * 转换成utf8
     * @param $text
     * @return string
     */
    function convert2Utf8($text)
    {
        $encoding = mb_detect_encoding($text, mb_detect_order(), false);
        if ($encoding == "UTF-8") {
            $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
        }
        $out = iconv(mb_detect_encoding($text, mb_detect_order(), false), "UTF-8//IGNORE", $text);

        return $out;
    }
}

if (!function_exists("langFmt")) {
    /**
     * 格式化国际化输出
     * @param $lang
     * @param $fmt
     * @return mixed
     */
    function langFmt($lang, $fmt)
    {
        $replaceKeys = array_keys($fmt);
        foreach ($replaceKeys as &$val) {
            $val = "{" . $val . "}";
        }
        return str_replace($replaceKeys, array_values($fmt), $lang);
    }
}

if(!function_exists("checkIP")){
    /**
     * IP格式检查
     * @param $ip
     * @return bool
     */
    function checkIP($ip){
        $regex = "((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))";
        !is_array($ip) && $ip = [$ip];
        foreach($ip as $val){
            if(preg_match($regex, $val, $matches) == false){
                return false;
            }
        }
        return true;
    }
}